package com.base.api.sys.impl;

import com.alibaba.fastjson.JSON;
import com.base.api.sys.ISysEnvironmentService;
import com.base.utils.RedisServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * 环境配置服务实现
 *
 * @author junw
 * @date 2018/5/10
 */
@Service
public class SysEnvironmentServiceImpl implements ISysEnvironmentService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private final StandardEnvironment env;

    private final ApplicationContext context;

    private final RedisServer redisServer;

    @Autowired
    public SysEnvironmentServiceImpl(ApplicationContext context, StandardEnvironment env, RedisServer redisServer) {
        this.env = env;
        this.context = context;
        this.redisServer = redisServer;
    }

    /**
     * 环境信息
     */
    private Map<Object, Object> config = new HashMap<>();

    @Override
    public String getEnvironmentInfo() {
        config.clear();
        config.put("BeanDefinitionCount", context.getBeanDefinitionCount());
        config.put("BeanDefinitionNames", context.getBeanDefinitionNames());
        getapplicationProperties();
        redisServer.set("env", JSON.toJSONString(config));
        return JSON.toJSONString(config);
    }

    /**
     * 获取classpath:/application.properties配置参数
     */
    private void getapplicationProperties(){
        PropertySource propertySource = env.getPropertySources().get("applicationConfig: [classpath:/application.properties]");
        Set<Map.Entry<Object, Object>> entries = ((Properties) propertySource.getSource()).entrySet();
        for (Map.Entry<Object, Object> entry : entries){
            config.put(entry.getKey(), entry.getValue());
        }
    }
}
